<template>
  <!-- 放置弹层组件 -->
  <el-dialog
    v-loading="loading"
    :title="title"
    :visible="dialogVisible"
    @close="colseDialog"
  >
    <el-form ref="formRef" label-width="100px" :model="form" :rules="formRules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" :disabled="isDisabled" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" placeholder="请选择" style="width:100%">
          <el-option
            v-for="item in simpleList"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="colseDialog">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { reqAddDept, reqEditDept, reqGetDeptInfoById, reqGetUserSimple } from '@/api/departments'
export default {
  props: {
    // 需要传入一个props变量来控制 显示或者隐藏
    dialogVisible: {
      type: Boolean,
      default: false
    },
    // 点击那个部门的数据
    nodeData: {
      type: Object,
      required: true
    },
    // 部门列表原始数据
    sourceDepts: {
      type: Array,
      required: true
    }
  },
  data() {
    // 同级部门禁止出现重复部门 自定义校验
    const checkNameRepeat = (rule, value, cb) => {
      if (this.form.id && value === this.nodeData.name) {
        return cb()
      }
      let arr = []
      if (this.form.id) {
        arr = this.sourceDepts.filter(item => item.pid === this.nodeData.pid)
      } else {
        arr = this.nodeData.children
      }
      console.log(this.sourceDepts)
      console.log(arr)
      console.log(this.nodeData.pid)
      const str = arr.some(item => item.name === value)
      str ? cb(new Error(`已经存在了${value}这个部门了`)) : cb()
    }
    // 所有部门不允许出现重复编码 自定义校验
    const checkCodeRepeat = (rule, value, cb) => {
      if (this.form.id && value === this.nodeData.code) {
        return cb()
      }
      const str = this.sourceDepts.some(item => item.code === value)
      str ? cb(`已经存在${value}这个部门编码了`) : cb()
    }
    return {
      // 对话框表单关联的数据
      form: {
        code: '',
        introduce: '',
        manager: '',
        name: ''
      },
      //   表单校验
      formRules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: ['blur', 'change'] },
          { min: 2, max: 50, message: '部门名称要求2-50个字符', trigger: ['blur', 'change'] },
          { validator: checkNameRepeat, trigger: ['blur', 'change'] }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: ['blur', 'change'] },
          { min: 2, max: 50, message: '部门编码要求2-50个字符', trigger: ['blur', 'change'] },
          { validator: checkCodeRepeat, trigger: ['blur', 'change'] }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: ['blur', 'change'] }
        ]
      },
      simpleList: [], // 部门负责人列表
      loading: false
    }
  },
  computed: {
    isDisabled() {
      return !!this.form.id
    },
    title() {
      return !this.form.id ? '编辑部门' : '添加部门'
    }
  },
  created() {
    this.getUserSimple()
  },
  methods: {
    // 点击关闭添加部门的对话框
    colseDialog() {
      this.$emit('close')
      // 重置表单校验和规则
      this.$refs.formRef.resetFields()
      // 恢复初始状态
      this.form = { code: '', introduce: '', manager: '', name: '' }
    },
    // 获取部门负责人列表
    async getUserSimple() {
      const res = await reqGetUserSimple()
      this.simpleList = res.data
    },
    // 点击确定添加部门
    handleSubmit() {
      // 预校验
      this.$refs.formRef.validate(async boo => {
        if (!boo) return this.$message.error('请正确填写信息')
        if (this.form.id) {
          // 编辑
          await reqEditDept(this.form)
          this.colseDialog()
        } else {
          // 新增
          const { code, message } = await reqAddDept({ ...this.form, pid: this.nodeData.id })
          if (code === 10000) {
          // 提示信息
            this.$message.success(message)
            // 关闭对话框
            this.colseDialog()
          }
        }
      })
    },
    // 根据id获取部门详情
    async getDeptInfo(id) {
      this.loading = true
      const { data } = await reqGetDeptInfoById(id)
      this.form = data
      this.loading = false
    }
  }
}
</script>
